import {Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {DhlCommonComponent} from '../dhlCommonComponent';
import {DhlCommonInputComponent} from '../dhlCommonInput';
import {ObjectUtil} from '../../../utils/object-util';


/**
 * name: 按钮名字
 * type: {
 *     primary，
 *     default，
 *     danger，
 *     gray,
 *     link
 * }
 */
@Component({
  selector: 'dhl-card',
  templateUrl: './dhl-card.component.html'
})
export class DhlCardComponent extends DhlCommonInputComponent implements OnInit {

  cardClass = [];
  list;
  @Input() component;
  @Input() showEdit = true;
  @Input() showDelete = true;
  @Input() showAdd = true;

  @Input() defaultCheckFirst = true;

  @Input()
  set datas(value) {
    value.forEach(() => {
      this.cardClass.push('card-div card-in-animation');
    });
    this.list = value;
    setTimeout(() => {
      this.cardClass = this.cardClass.map(() => 'card-div');
      if (this.defaultCheckFirst) {
        this.click(0);
      }
    }, 300);

  };

  get datas() {
    return this.list;
  }


  @Output() addClick = new EventEmitter();
  @Output() editClick = new EventEmitter();
  @Output() deleteClick = new EventEmitter();
  @Output() cardClick = new EventEmitter();


  click(index) {
    let isCheck = false;
    this.inputValue = undefined;
    let data;
    for (let i = 0; i < this.datas.length; i++) {
      if (i == index && this.cardClass[i] != 'card-div card-active') {
        this.cardClass[i] = 'card-div card-active';
        this.inputValue = this.datas[i].id;
        isCheck = true;
      } else {
        this.cardClass[i] = 'card-div';
      }
    }

    if (isCheck) {
      data = this.list[index];
    }
    this.cardClick.emit({index, data});
  }


  openConfirm(event, index) {
    event.stopPropagation();
    this.messageService.openConfirm('确定要删除吗？', () => {
      this.doDelete(event, index);
    });
  }


  doDelete(event, index) {
    this.deleteClick.emit({
      finishedDelete: () => {
        this.finishedDelete(index);
      },
      data: this.list[index],
      index
    });
  }


  editClickEvent(event, index) {
    event.stopPropagation();
    this.editClick.emit({index, data: this.list[index]});
  }

  addClickEvent() {
    this.addClick.emit({
      finishedAdd: () => {
        this.afterdAdd();
      }
    });
  }

  finishedDelete(index) {
    const cardc = this.cardClass[index].replace('card-in-animation', '');
    this.cardClass.splice(index, 1, cardc + ' card-close-animation');
    setTimeout(() => {
      this.cardClass.splice(index, 1);
      this.datas.splice(index, 1);
    }, 300);
  }

  afterdAdd() {
    this.cardClass.push('card-div card-in-animation');
    setTimeout(() => {
      this.cardClass.pop();
      this.cardClass.push('card-div');
    }, 300);
  }

  ngOnInit(): void {
  }


}














